/*
 * Copyright 2011 CraneLeeon authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.crane.webtemplate.dao;

import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import javax.management.ObjectName;
import org.hibernate.SessionFactory;
import org.hibernate.jmx.StatisticsService;

/**
 * JMX agent class.
 * You may use the New JMX MBean wizard to create a Managed Bean.
 * @author Crane Leeon
 */
public class JmxAgent {
    /**
     * Instantiate and register your MBeans.
     */
    public void init(SessionFactory sf) throws Exception {
        // Define ObjectName of the MBean
        ObjectName on = new ObjectName
                ("Hibernate:type=statistics,application=Phalanx");
        // Enable Hibernate JMX Statistics
        StatisticsService statsMBean = new StatisticsService();
        statsMBean.setSessionFactory(sf);
        statsMBean.setStatisticsEnabled(true);
        if(mbs.isRegistered(on)) mbs.unregisterMBean(on);
        mbs.registerMBean(statsMBean, on);
        /**
         * Enable Ehcache JMX Statistics
         * Use CacheManager.getInstance() instead of new CacheManager()
         * as net.sf.ehcache.hibernate.SingletonEhCacheProvider is used
         * to ensure reference to the same CacheManager instance as used
         * by Hibernate
         */
//        CacheManager cacheMgr = CacheManager.getInstance();
//        ManagementService.registerMBeans(cacheMgr, mbs, true, true, true, true);
    }
    
    /**
     * Returns an agent singleton.
     */
    public synchronized static JmxAgent getDefault(SessionFactory sf) throws Exception {
        if(singleton == null) {
            singleton = new JmxAgent();
            singleton.init(sf);
        }
        return singleton;
    }
    
    public MBeanServer getMBeanServer() {
        return mbs;
    }
    
    // Platform MBeanServer used to register your MBeans
    private final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    
    // Singleton instance
    private static JmxAgent singleton;
}


